﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Helpers;
using CNotebook;
using CNotebook.Inventory;

namespace NotebookS2
{
    public partial class ConsignmentOrder : RibbonForm
    {
        public ConsignmentOrder()
        {
            InitializeComponent();
        }

        public int ObjectType { get { return 2; } }
        public Keys UsedKey = Keys.None;

        #region Properties
        public string ConnectionString { get; set; }
        public string ActiveUserID { get; set; }
        public DataTable OrderLineItems { get; set; }
        public string DefaultPriceList { get; set; }
        public string DefaultWarehouse { get; set; }
        public bool IsMultipleWarehouse { get; set; }
        public string VATCode { get; set; }
        public string VATRate { get; set; }
        public bool IsInclusive { get; set; }
        #endregion

        #region Initialization

        private static DataTable GetTable()
        {
            DataTable table = new DataTable();
            table.Columns.Add("LineNum", typeof(string));
            table.Columns.Add("ItemCode", typeof(string));
            table.Columns.Add("ItemDesc", typeof(string));
            table.Columns.Add("UoM", typeof(string));
            table.Columns.Add("Qty", typeof(double));
            table.Columns.Add("CQty", typeof(double));
            table.Columns.Add("PriceListCode", typeof(string));
            table.Columns.Add("UnitPrice", typeof(double));
            table.Columns.Add("IsFree", typeof(bool));
            table.Columns.Add("DiscPrcnt", typeof(double));
            table.Columns.Add("Discount", typeof(double));
            table.Columns.Add("TotalLineDisc", typeof(double));
            table.Columns.Add("Amount", typeof(double));
            table.Columns.Add("ItemGuID", typeof(string));

            return table;

        }

        void InitializeSeries()
        {

            string sOrderSeries = "400";
            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();

            lblValidUntilDeliveryDate.Text = "Date Needed:";
            if (oSeries.IsAutoNumber(sOrderSeries) == true)
            {
                txtDocumentNumber.Properties.ReadOnly = true;
                txtDocumentNumber.Text = "##########";

            }
            oSeries.Close();

        }

        #endregion

        #region Functions
        void BindWarehouseAndExclude(string _ExcludeWarehouse)
        {
            WarehouseManager oManager = new WarehouseManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();


            cboDestination.Properties.DataSource = oManager.GetWarehouseAndExclude(_ExcludeWarehouse);
            cboDestination.Properties.DisplayMember = "Dscription";
            cboDestination.Properties.ValueMember = "Code";

            cboDestination.Refresh();


            oManager.Close();
        }
        public void PrintPreview()
        {
            PRNT_SO oPrint = new PRNT_SO();

            oPrint.ConnectionString = this.ConnectionString;
            oPrint.DocumentNumber = txtDocumentNumber.Text;

            oPrint.WindowState = FormWindowState.Maximized;
            oPrint.ShowDialog();
        }

        void EnableControls()
        {
            if (this.IsMultipleWarehouse == true)
            {
                cboLocation.Enabled = true;
            }
            cboDestination.Enabled = true;
            txtStoreCode.Enabled = true;
            txtCardCode.Enabled = true;
            txtCardName.Enabled = true;
            txtContactPerson.Enabled = true;
            txtReference.Enabled = true;
            txtBillTo.Enabled = true;
            txtShipTo.Enabled = true;
            txtDocumentNumber.Enabled = true;
            dtPostDate.Enabled = true;
            dtDeliveryDate.Enabled = true;
            dtDocDate.Enabled = true;

            cboSalesman.Enabled = true;
            txtRemarks.Enabled = true;
            txtGrossAmount.Enabled = true;
            txtTotalLineDiscount.Enabled = true;
            txtDisc1.Enabled = true;
            txtDisc2.Enabled = true;
            txtDisc3.Enabled = true;
            txtDisc4.Enabled = true;
            txtTotalDiscount.Enabled = true;
            txtVAT.Enabled = true;
            txtNetAmt.Enabled = true;
            txtPaymentTerms.Enabled = false;
            btnAdd.Enabled = true;

            foreach (DevExpress.XtraGrid.Columns.GridColumn oColumn in gridView1.Columns)
            {
                if (oColumn.Name == "Code" || oColumn.Name == "Quantity" || oColumn.Name == "Free" || oColumn.Name == "UnitPric" || oColumn.Name == "Discount" || oColumn.Name == "UnitMeasure")
                {
                    oColumn.OptionsColumn.AllowEdit = true;
                }
            }

        }

        void DisableControls()
        {
            cboDestination.Enabled = false;
            cboLocation.Enabled = false;
            txtStoreCode.Enabled = false;
            txtCardCode.Enabled = false;
            txtCardName.Enabled = false;
            txtContactPerson.Enabled = false;
            txtReference.Enabled = false;
            txtBillTo.Enabled = false;
            txtShipTo.Enabled = false;
            txtDocumentNumber.Enabled = false;
            dtPostDate.Enabled = false;
            dtDeliveryDate.Enabled = false;
            dtDocDate.Enabled = false;

            cboSalesman.Enabled = false;
            txtRemarks.Enabled = false;
            txtGrossAmount.Enabled = false;
            txtTotalLineDiscount.Enabled = false;
            txtDisc1.Enabled = false;
            txtDisc2.Enabled = false;
            txtDisc3.Enabled = false;
            txtDisc4.Enabled = false;
            txtTotalDiscount.Enabled = false;
            txtVAT.Enabled = false;
            txtNetAmt.Enabled = false;
            txtPaymentTerms.Enabled = false;
            btnAdd.Enabled = false;
            foreach (DevExpress.XtraGrid.Columns.GridColumn oColumn in gridView1.Columns)
            {
                oColumn.OptionsColumn.AllowEdit = false;
            }

        }

        string GetNewSeries()
        {
            string _SERIES = "";
            string _DOCTYPE = "400";

            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();
            if (oSeries.IsAutoNumber(_DOCTYPE) == true)
            {
                _SERIES = oSeries.GetNewSeries(_DOCTYPE);
            }
            else
            {
                _SERIES = txtDocumentNumber.Text;
            }
            oSeries.Close();

            return _SERIES;
        }

        void ComputeTotal()
        {
            try
            {
                double _GrossAmount = 0;
                double _NetAmount = 0;
                double _LineDiscount = 0;

                foreach (DataRow oRow in this.OrderLineItems.Rows)
                {
                    if (oRow["Amount"] != DBNull.Value)
                    {
                        byte IsFree = Convert.ToByte(oRow["IsFree"]);
                        int iIsFree = Convert.ToInt16(IsFree);

                        if (iIsFree == 0)
                        {
                            _GrossAmount = _GrossAmount + (Convert.ToDouble(oRow["Qty"]) * Convert.ToDouble(oRow["CQty"])) * Convert.ToDouble(oRow["UnitPrice"]);
                        }

                        _NetAmount = _NetAmount + (Convert.ToDouble(oRow["Amount"]));
                        if (oRow["TotalLineDisc"] == DBNull.Value)
                        {
                            oRow["TotalLineDisc"] = 0;
                        }
                        _LineDiscount = _LineDiscount + (Convert.ToDouble(oRow["TotalLineDisc"]));
                    }
                }

                double _VAT = 0;
                double _VolumeDiscount = 0;




                if (txtTotalDiscount.Text != "")
                {
                    try
                    {
                        _VolumeDiscount = Convert.ToDouble(txtTotalDiscount.Text);
                    }
                    catch
                    {
                        _VolumeDiscount = 0;
                    }
                }
                if (this.VATCode != "NON-VAT")
                {
                    if (this.IsInclusive == true)
                    {

                        _VAT = _NetAmount - ((_NetAmount - _VolumeDiscount) / Convert.ToDouble(this.VATRate));
                        _VAT = Convert.ToDouble(_VAT.ToString("##.00"));
                        txtVAT.Text = _VAT.ToString();
                    }
                    else
                    {
                        txtVAT.Text = "0";
                    }
                }

                txtTotalLineDiscount.Text = _LineDiscount.ToString("#,###.00");
                txtGrossAmount.Text = _GrossAmount.ToString("#,###.00");

                txtNetAmt.Text = _NetAmount.ToString("#,###.00");

                ApplyVolumeDiscount();
            }
            catch
            {
            }

        }

        void ApplyVolumeDiscount()
        {

            double _GrossAmount = 0;
            double _NetAmount = 0;
            double _TotalLineDiscount = 0;
            double _VatAmount = 0;
            //RemoveBlankLastRowFirst();

            foreach (DataRow oRow in this.OrderLineItems.Rows)
            {

                if (oRow["Qty"] == DBNull.Value)
                {
                    oRow["Qty"] = 0;
                }
                if (oRow["CQty"] == DBNull.Value)
                {
                    oRow["CQty"] = 0;
                }
                if (oRow["UnitPrice"] == DBNull.Value)
                {
                    oRow["UnitPrice"] = 0;
                }
                if (oRow["TotalLineDisc"] == DBNull.Value)
                {
                    oRow["TotalLineDisc"] = 0;
                }
                if (oRow["IsFree"] == DBNull.Value)
                {
                    oRow["IsFree"] = false;
                }
                bool IsFree = Convert.ToBoolean(oRow["IsFree"]);

                if (IsFree != true)
                {
                    _GrossAmount = _GrossAmount + (Convert.ToDouble(oRow["Qty"]) * Convert.ToDouble(oRow["CQty"])) * Convert.ToDouble(oRow["UnitPrice"]);
                    _TotalLineDiscount = _TotalLineDiscount + Convert.ToDouble(oRow["TotalLineDisc"]);
                }

            }

            txtDisc1.Text = txtDisc1.Text.Replace("%", "");
            txtDisc2.Text = txtDisc2.Text.Replace("%", "");
            txtDisc3.Text = txtDisc3.Text.Replace("%", "");
            txtDisc4.Text = txtDisc4.Text.Replace("%", "");


            string sDiscount1 = txtDisc1.Text.Replace("%", "");
            string sDiscount2 = txtDisc2.Text.Replace("%", "");
            string sDiscount3 = txtDisc3.Text.Replace("%", "");
            string sDiscount4 = txtDisc4.Text.Replace("%", "");


            double _disc1 = 0;
            double _disc2 = 0;
            double _disc3 = 0;
            double _disc4 = 0;


            _disc1 = Convert.ToDouble(sDiscount1);
            _disc2 = Convert.ToDouble(sDiscount2);
            _disc3 = Convert.ToDouble(sDiscount3);

            double _TotalDiscount = 0;

            double _discount1 = 0;
            double _discount2 = 0;
            double _discount3 = 0;
            double _discount4 = 0;

            _disc1 = Convert.ToDouble(sDiscount1);
            _disc2 = Convert.ToDouble(sDiscount2);
            _disc3 = Convert.ToDouble(sDiscount3);


            if (txtDisc4.Text == "")
            {
                _disc4 = 0;
            }
            else
            {
                _disc4 = Convert.ToDouble(sDiscount4);
            }

            if (_disc1 > 0)
            {
                _discount1 = (_GrossAmount - _TotalLineDiscount) * (_disc1 / 100);

                _TotalDiscount = (_GrossAmount - _TotalLineDiscount) - _discount1;
            }
            if (_disc2 > 0)
            {
                _discount2 = (_TotalDiscount * (_disc2 / 100));
                _TotalDiscount = _TotalDiscount - _discount2;

            }
            if (_disc3 > 0)
            {
                _discount3 = (_TotalDiscount * (_disc3 / 100));
                _TotalDiscount = _TotalDiscount - _discount3;
            }

            if (_disc4 > 0)
            {
                _discount4 = (_TotalDiscount * (_disc4 / 100));
                _TotalDiscount = _TotalDiscount - _discount4;
            }

            _TotalDiscount = (_discount1 + _discount2 + _discount3 + _discount4);
            txtTotalDiscount.Text = _TotalDiscount.ToString("#,###.00");



            txtGrossAmount.Text = _GrossAmount.ToString("#,###.00");
            txtTotalLineDiscount.Text = _TotalLineDiscount.ToString("#,###.00");

            _NetAmount = (_GrossAmount - _TotalDiscount) - _TotalLineDiscount;

            if (this.VATCode != "NON-VAT")
            {
                if (this.VATCode == "VAT Inclusive")
                {
                    _VatAmount = _NetAmount - (_NetAmount / Convert.ToDouble(this.VATRate));
                }
                else if (this.VATCode == "VAT Exclusive")
                {
                    _VatAmount = _NetAmount - (_NetAmount / Convert.ToDouble(this.VATRate)); ;
                    _NetAmount = _NetAmount + _VatAmount;
                }
            }


            txtVAT.Text = _VatAmount.ToString("#,###.00");
            txtNetAmt.Text = _NetAmount.ToString("#,###.00");


            #region Returning Percent Sign
            if (_disc1 > 0)
            {
                txtDisc1.Text = _disc1.ToString("#.0000") + "%";
            }
            else
            {
                txtDisc1.Text = "0%";
            }
            if (_disc2 > 0)
            {
                txtDisc2.Text = _disc2.ToString("#.0000") + "%";
            }
            else
            {
                txtDisc2.Text = "0%";
            }
            if (_disc3 > 0)
            {
                txtDisc3.Text = _disc3.ToString("#.0000") + "%";
            }
            else
            {
                txtDisc3.Text = "0%";
            }

            if (_disc4 > 0)
            {
                txtDisc4.Text = _disc4.ToString("#.0000") + "%";
            }
            else
            {
                txtDisc4.Text = "0%";
            }
            #endregion


        }

        void BindWarehouse()
        {
            WarehouseManager oManager = new WarehouseManager();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();
            DataTable oTable = new DataTable();

            oTable = oManager.GetWarehouse();

            
            cboLocation.Visible = false;
            cboLocation.Properties.DataSource = oTable;
            cboLocation.Properties.DisplayMember = "Dscription";
            cboLocation.Properties.ValueMember = "Code";
            
            DevExpress.XtraEditors.Controls.LookUpColumnInfo col;

            col = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Dscription", "Dscription", 100);

            col.SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;

            cboLocation.Properties.ShowHeader = false;
            cboLocation.Properties.Columns.Add(col);

            cboLocation.Visible = true;


            //cboLocation.Visible = false;
            //cboLocation.DataSource = oTable;
            //cboLocation.DisplayMember = "Dscription";
            //cboLocation.ValueMember = "Code";

            //cboLocation.Refresh();
            //cboLocation.Visible = true;
            oManager.Close();





        }

        void BindSalesMan()
        {
            AccountManager oManager = new AccountManager();
            DataTable oTable = new DataTable();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();


            oTable = oManager.GetAccounts("Salesman");
            cboSalesman.Visible = false;
            cboSalesman.Properties.DataSource = oTable;
            cboSalesman.Properties.DisplayMember = "AccountHolder";
            cboSalesman.Properties.ValueMember = "AcctCode";

            DevExpress.XtraEditors.Controls.LookUpColumnInfo col;

            col = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("AcctCode", "AcctName", 100);

            col.SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;

            cboSalesman.Refresh();
            cboSalesman.Visible = true;
            oManager.Close();

        }

        void RemoveBlankLastRowFirst()
        {
            try
            {
                int iCount = -1;
                gridView1.MoveLast();

                int[] oRow = gridView1.GetSelectedRows();

                iCount = oRow[0];
                string sItemCode = "";


                sItemCode = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemCode"]).ToString();

                if (sItemCode.Trim() == "")
                {
                    gridView1.DeleteRow(iCount);
                }
            }
            catch
            {
            }

        }

        public void ShowSearch()
        {
            FND_CONSIGMENT oSearchDocument = new FND_CONSIGMENT();

            oSearchDocument.ConnectionString = this.ConnectionString;
            oSearchDocument.ShowDialog();

            string sDocumentNumber = oSearchDocument.DocumentNumber;


            if (sDocumentNumber != null || sDocumentNumber.Trim() != "")
            {
                ConsignmentManager oManager = new ConsignmentManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                DataRow oRow = oManager.GetOrder(sDocumentNumber);


                #region Header
                txtDocumentNumber.Text = oRow["DocNum"].ToString();
                txtStatus.Text = oRow["DocStatus"].ToString();
                dtPostDate.EditValue = (DateTime)oRow["PostingDate"];
                dtDeliveryDate.EditValue = (DateTime)oRow["DueDate"];
                dtDocDate.EditValue = (DateTime)oRow["DocDate"];
                txtStoreCode.Text = oRow["StoreCode"].ToString();
                txtCardCode.EditValue = oRow["CardCode"].ToString();
                AddressBookManager oCardManager = new AddressBookManager();
                oCardManager.Connection = oManager.Connection;
                this.DefaultPriceList = oCardManager.GetPriceListCode(txtCardCode.Text);
                txtCardName.EditValue = oRow["CardName"].ToString();
                txtContactPerson.EditValue = oRow["ContactPerson"].ToString();
                txtPaymentTerms.Text = oRow["PaymentTerms"].ToString();
                txtReference.EditValue = oRow["Reference"].ToString();
                txtBillTo.EditValue = oRow["BillTo"].ToString();
                txtShipTo.EditValue = oRow["ShipTo"].ToString();
                cboSalesman.EditValue = oRow["SalesMan"].ToString();
                cboLocation.EditValue = oRow["Location"].ToString();
                cboDestination.EditValue = oRow["Destination"].ToString();
                txtRemarks.EditValue = oRow["Remarks"].ToString();

                //if (oRow["Location"] != DBNull.Value)
                //{
                //    cboLocation.SelectedValue = oRow["Location"].ToString();
                //}


                if (oRow["VATCode"] != DBNull.Value)
                {
                    this.VATCode = oRow["VATCode"].ToString();
                }

                this.VATRate = oRow["VATRate"].ToString();

                if (oRow["IsVATInclusive"] != DBNull.Value)
                {

                    if (oRow["IsVATInclusive"].ToString() == "Y")
                    {
                        this.IsInclusive = true;
                    }
                    else
                    {
                        this.IsInclusive = false;
                    }
                }

                txtGrossAmount.EditValue = oRow["GrossAmount"].ToString();
                txtVAT.EditValue = oRow["VATAmount"].ToString();
                txtDisc1.EditValue = oRow["Discount1"].ToString();
                txtDisc2.EditValue = oRow["Discount2"].ToString();
                txtDisc3.EditValue = oRow["Discount3"].ToString();
                txtDisc4.EditValue = oRow["Discount4"].ToString();
                txtTotalDiscount.EditValue = oRow["TotalDiscount"].ToString();
                txtNetAmt.EditValue = oRow["NetAmount"].ToString();
                #endregion

                #region Line Items
                this.OrderLineItems = oManager.GetOrderLineItems(sDocumentNumber);
                gridControl1.DataSource = this.OrderLineItems;
                gridControl1.Refresh();

                if (txtStatus.Text == "Draft")
                {
                    if (gridView1.DataRowCount <= 0)
                    {
                        gridView1.AddNewRow();

                        gridView1.Focus();
                        SendKeys.Send("{DOWN}");
                    }
                }

                #endregion

                oManager.Close();

                btnAdd.Text = "Update";

                ComputeTotal();
                ApplyVolumeDiscount();

                //btnAdd_Click(null, null);

            }

            string _USR_AUTHORIZATION = ApplyAuthorization();
            if (_USR_AUTHORIZATION == "No Access")
            {
                btnCancel_Click(null, null);
            }

        }

        void CancelOrder(string sDocNumber)
        {
            if (MessageBox.Show("Are you sure you want to cancel this document?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                ConsignmentManager oManager = new ConsignmentManager();
                ConsignmentUnit oUnit = new ConsignmentUnit();
                #region Update Sales Order
                #region Header Sales Order

                oUnit.DocumentNumber = txtDocumentNumber.Text;
                oUnit.DocumentStatus = txtStatus.Text;
                oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                oUnit.DocDate = (DateTime)dtDocDate.EditValue;

                oUnit.StoreCode = txtStoreCode.Text;
                oUnit.CardCode = txtCardCode.Text;
                oUnit.CardName = txtCardName.Text;
                oUnit.ContactPerson = txtContactPerson.Text;
                oUnit.PaymentTerms = txtPaymentTerms.Text;
                oUnit.Reference = txtReference.Text;
                oUnit.ShipTo = txtShipTo.Text;
                oUnit.BillTo = txtBillTo.Text;
                oUnit.Location = cboLocation.EditValue.ToString();
                if (cboDestination.EditValue == null)
                {
                    MessageBox.Show("Please select destination", "Destination", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                oUnit.Destination = cboDestination.EditValue.ToString();
                //if (cboLocation.SelectedValue != null)
                //{
                //    oUnit.Location = cboLocation.SelectedValue.ToString();
                //}
                //else
                //{
                //    oUnit.Location = "";
                //}

                if (cboSalesman.EditValue != null)
                {
                    oUnit.SalesMan = cboSalesman.EditValue.ToString();
                }
                else
                {
                    oUnit.SalesMan = "";
                }

                oUnit.Remarks = txtRemarks.Text;

                oUnit.TaxCode = this.VATCode.ToString();
                oUnit.TaxRate = Convert.ToDouble(this.VATRate.ToString());
                if (oUnit.TaxCode != "NON-VAT")
                {
                    oUnit.IsVATInclusive = this.IsInclusive == true ? "Y" : "N";
                }
                else
                {
                    oUnit.IsVATInclusive = "N/A";
                }



                oUnit.GrossAmnt = Convert.ToDouble(txtGrossAmount.Text.Replace(",", "").ToString());
                oUnit.VATAmt = Convert.ToDouble(txtVAT.Text.Replace(",", "").ToString());
                oUnit.TotalLineDisc = Convert.ToDouble(txtTotalLineDiscount.Text.Replace(",", "").ToString());

                oUnit.Discount1 = txtDisc1.Text;
                oUnit.Discount2 = txtDisc2.Text;
                oUnit.Discount3 = txtDisc3.Text;
                oUnit.Discount4 = txtDisc4.Text;

                oUnit.TotalDiscount = Convert.ToDouble(txtTotalDiscount.Text.Replace(",", "").ToString());
                oUnit.NetAmount = Convert.ToDouble(txtNetAmt.Text.Replace(",", "").ToString());
                oUnit.DateModified = System.DateTime.Now;
                oUnit.ModifiedBy = this.ActiveUserID;

                #endregion

                oUnit.LineItems = this.OrderLineItems;

                #region Updating Portion
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.UpdateOrder(oUnit);
                oManager.Close();
                #endregion

                #endregion
                oManager = new ConsignmentManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.CancelOrder(sDocNumber);
                oManager.Close();

                txtStatus.Text = "Canceled";
            }

        }

        void PostOrder(string sDocNumber)
        {
            if (MessageBox.Show("Are you sure you want to post this document?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {

                ConsignmentManager oManager = new ConsignmentManager();
                ConsignmentUnit oUnit = new ConsignmentUnit();
                #region Update Sales Order
                #region Header Sales Order

                oUnit.DocumentNumber = txtDocumentNumber.Text;
                oUnit.DocumentStatus = txtStatus.Text;
                oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                oUnit.DocDate = (DateTime)dtDocDate.EditValue;

                oUnit.StoreCode = txtStoreCode.Text;
                oUnit.CardCode = txtCardCode.Text;
                oUnit.CardName = txtCardName.Text;
                oUnit.ContactPerson = txtContactPerson.Text;
                oUnit.PaymentTerms = txtPaymentTerms.Text;
                oUnit.Reference = txtReference.Text;
                oUnit.ShipTo = txtShipTo.Text;
                oUnit.BillTo = txtBillTo.Text;
                oUnit.Location = cboLocation.EditValue.ToString();

                if (cboDestination.EditValue == null)
                {
                    MessageBox.Show("Please select destination", "Destination", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                oUnit.Destination = cboDestination.EditValue.ToString();

                if (cboSalesman.EditValue != null)
                {
                    oUnit.SalesMan = cboSalesman.EditValue.ToString();
                }
                else
                {
                    oUnit.SalesMan = "";
                }

                oUnit.Remarks = txtRemarks.Text;

                oUnit.TaxCode = this.VATCode.ToString();
                oUnit.TaxRate = Convert.ToDouble(this.VATRate.ToString());
                if (oUnit.TaxCode != "NON-VAT")
                {
                    oUnit.IsVATInclusive = this.IsInclusive == true ? "Y" : "N";
                }
                else
                {
                    oUnit.IsVATInclusive = "N/A";
                }



                oUnit.GrossAmnt = Convert.ToDouble(txtGrossAmount.Text.Replace(",", "").ToString());
                oUnit.VATAmt = Convert.ToDouble(txtVAT.Text.Replace(",", "").ToString());
                oUnit.TotalLineDisc = Convert.ToDouble(txtTotalLineDiscount.Text.Replace(",", "").ToString());

                oUnit.Discount1 = txtDisc1.Text;
                oUnit.Discount2 = txtDisc2.Text;
                oUnit.Discount3 = txtDisc3.Text;
                oUnit.Discount4 = txtDisc4.Text;

                oUnit.TotalDiscount = Convert.ToDouble(txtTotalDiscount.Text.Replace(",", "").ToString());
                oUnit.NetAmount = Convert.ToDouble(txtNetAmt.Text.Replace(",", "").ToString());
                oUnit.DateModified = System.DateTime.Now;
                oUnit.ModifiedBy = this.ActiveUserID;

                #endregion

                oUnit.LineItems = this.OrderLineItems;

                #region Updating Portion
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.UpdateOrder(oUnit);
                oManager.Close();
                #endregion

                #endregion
                oManager = new ConsignmentManager();
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.PostOrder(sDocNumber);
                oManager.Close();

                txtStatus.Text = "Posted";

            }
        }

        void CloseOrder(string sDocNumber)
        {
            if (MessageBox.Show("Are you sure you want to close this document?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                ConsignmentManager oManager = new ConsignmentManager();
                ConsignmentUnit oUnit = new ConsignmentUnit();
                #region Update Sales Order
                #region Header Sales Order

                oUnit.DocumentNumber = txtDocumentNumber.Text;
                oUnit.DocumentStatus = txtStatus.Text;
                oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                oUnit.DocDate = (DateTime)dtDocDate.EditValue;

                oUnit.StoreCode = txtStoreCode.Text;
                oUnit.CardCode = txtCardCode.Text;
                oUnit.CardName = txtCardName.Text;
                oUnit.ContactPerson = txtContactPerson.Text;
                oUnit.PaymentTerms = txtPaymentTerms.Text;
                oUnit.Reference = txtReference.Text;
                oUnit.ShipTo = txtShipTo.Text;
                oUnit.BillTo = txtBillTo.Text;
                oUnit.Location = cboLocation.EditValue.ToString();
                if (cboDestination.EditValue == null)
                {
                    MessageBox.Show("Please select destination", "Destination", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                oUnit.Destination = cboDestination.EditValue.ToString();
                if (cboSalesman.EditValue != null)
                {
                    oUnit.SalesMan = cboSalesman.EditValue.ToString();
                }
                else
                {
                    oUnit.SalesMan = "";
                }

                oUnit.Remarks = txtRemarks.Text;

                oUnit.TaxCode = this.VATCode.ToString();
                oUnit.TaxRate = Convert.ToDouble(this.VATRate.ToString());
                if (oUnit.TaxCode != "NON-VAT")
                {
                    oUnit.IsVATInclusive = this.IsInclusive == true ? "Y" : "N";
                }
                else
                {
                    oUnit.IsVATInclusive = "N/A";
                }



                oUnit.GrossAmnt = Convert.ToDouble(txtGrossAmount.Text.Replace(",", "").ToString());
                oUnit.VATAmt = Convert.ToDouble(txtVAT.Text.Replace(",", "").ToString());
                oUnit.TotalLineDisc = Convert.ToDouble(txtTotalLineDiscount.Text.Replace(",", "").ToString());

                oUnit.Discount1 = txtDisc1.Text;
                oUnit.Discount2 = txtDisc2.Text;
                oUnit.Discount3 = txtDisc3.Text;
                oUnit.Discount4 = txtDisc4.Text;

                oUnit.TotalDiscount = Convert.ToDouble(txtTotalDiscount.Text.Replace(",", "").ToString());
                oUnit.NetAmount = Convert.ToDouble(txtNetAmt.Text.Replace(",", "").ToString());
                oUnit.DateModified = System.DateTime.Now;
                oUnit.ModifiedBy = this.ActiveUserID;

                #endregion

                oUnit.LineItems = this.OrderLineItems;

                #region Updating Portion
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.UpdateOrder(oUnit);
                oManager.Close();
                #endregion

                #endregion
                oManager = new ConsignmentManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.CloseOrder(sDocNumber);
                oManager.Close();

                txtStatus.Text = "Closed";

            }
        }

        bool IsComplete()
        {
            if (cboDestination.EditValue == null)
            {
                return false;
            }
            if (txtCardCode.Text == "")
            {
                return false;
            }

            if (OrderLineItems.Rows.Count <= 0)
            {
                return false;
            }

            foreach (DataRow oRow in this.OrderLineItems.Rows)
            {
                if (oRow.RowState != DataRowState.Deleted)
                {
                    if (oRow["Qty"] == DBNull.Value || Convert.ToDouble(oRow["Qty"]) == 0 || Convert.ToString(oRow["Qty"]) == "")
                    {
                        return false;
                    }
                }
            }

            return true;
        }
        #endregion


        void BindUoM(string sItemCode, DevExpress.XtraEditors.Repository.RepositoryItemComboBox oCbo)
        {
            UoMManager oManager = new UoMManager();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            DataTable _table = oManager.GetUnitMeasures(sItemCode);

            oManager.Close();

            oCbo.Items.Clear();
            foreach (DataRow oRow in _table.Rows)
            {
                oCbo.Items.Add(oRow["UoM"].ToString());
            }

        }

        string ApplyAuthorization()
        {
            UserManager oManager = new UserManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            string iAccessType = oManager.GetAccessType(this.ObjectType, this.ActiveUserID);

            oManager.Close();

            switch (iAccessType)
            {
                case "Full Access":
                    FullAccess();
                    break;
                case "Read Only":
                    ApplyReadOnly();
                    break;
                case "No Access":
                    NoAccess();
                    break;
            }

            return iAccessType;
        }


        int ApplyReadOnly()
        {
            DisableControls();

            txtStatus.Properties.Buttons[0].Enabled = false;
            txtStatus.Properties.Buttons[1].Enabled = false;

            btnCopyToDelivery.Enabled = false;
            btnCreateTransfer.Enabled = false;
            return 2;
        }

        int FullAccess()
        {
            txtStatus.Properties.Buttons[0].Enabled = true;
            txtStatus.Properties.Buttons[1].Enabled = true;
            btnCopyToDelivery.Enabled = true;
            btnCreateTransfer.Enabled = true;
            return 1;
        }

        int NoAccess()
        {
            MessageBox.Show("You have no right to access this module!!!!", "Security Policy", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            return 3;

        }

        #region Form Events

        private void SalesOrder_Load(object sender, EventArgs e)
        {
            gridView1.HorzScrollVisibility = DevExpress.XtraGrid.Views.Base.ScrollVisibility.Always;
            txtPaymentTerms.Enabled = false;
            btnCopyToDelivery.Visible = false;
            btnCreateTransfer.Visible = false;
            dtPostDate.EditValue = System.DateTime.Now;
            dtDeliveryDate.EditValue = System.DateTime.Now;
            dtDocDate.EditValue = System.DateTime.Now;

            BindWarehouse();
            
            cboLocation.EditValue = this.DefaultWarehouse;
            BindWarehouseAndExclude(cboLocation.Text);
            if (this.IsMultipleWarehouse == false)
            {
                cboLocation.Enabled = false;
            }

            BindSalesMan();

            if (this.OrderLineItems == null)
            {
                this.OrderLineItems = GetTable();
            }

            gridControl1.DataSource = this.OrderLineItems;
            gridControl1.Refresh();


            if (gridView1.DataRowCount <= 0)
            {
                gridView1.AddNewRow();

            }

            InitializeSeries();
        }

        private void txtCardCode_Properties_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_BP _SearchBP = new FND_BP();

            AddressBookManager oBPManager = new AddressBookManager();
            TaxManager oTxManager = new TaxManager();

            try
            {
                _SearchBP.ConnectionString = this.ConnectionString;
                _SearchBP.BusinessPartnerType = "Customer";
                _SearchBP.ShowDialog();

                txtStoreCode.Text = _SearchBP.StoreCode;
                txtCardCode.Text = _SearchBP.CardCode;
                txtCardName.Text = _SearchBP.CardName;
                txtBillTo.Text = _SearchBP.Address.Trim();
                txtPaymentTerms.Text = _SearchBP.PaymentTerm.ToString().Trim();
                txtContactPerson.Text = _SearchBP.ContactPerson;
                this.DefaultPriceList = _SearchBP.PriceList;
                this.VATCode = _SearchBP.VATCode;
                try
                {
                    txtDisc1.Text = _SearchBP.Discount1.ToString() + "%";
                    txtDisc2.Text = _SearchBP.Discount2.ToString() + "%";
                    txtDisc3.Text = _SearchBP.Discount3.ToString() + "%";
                    txtDisc4.Text = _SearchBP.Discount4.ToString() + "%";
                }
                catch
                {
                }

                //cboCurrency.Text 
                oTxManager.ConnectionString = this.ConnectionString;
                oTxManager.Open();


                this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();

                this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;


              

                oTxManager.Close();

                if (_SearchBP.BuyerSalesMan != "")
                {
                    cboSalesman.EditValue = _SearchBP.BuyerSalesMan;
                }

                _SearchBP.Dispose();
            }
            catch
            {
            }
        }

        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            string _USR_AUTHORIZATION = ApplyAuthorization();
            if (_USR_AUTHORIZATION == "No Access" || _USR_AUTHORIZATION == "Read Only")
            {
                return;
            }
            try
            {
                int iCount = gridView1.FocusedRowHandle;


                if (e.KeyCode == Keys.Delete)
                {
                    if (txtStatus.Text == "Draft")
                    {
                        if (MessageBox.Show("Are you sure you want to delete this Row?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {

                            if (gridView1.IsLastRow)
                            {
                                string sItemCode = "";


                                iCount = gridView1.FocusedRowHandle;
                                sItemCode = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemCode"]).ToString();


                                if (sItemCode != "")
                                {
                                    gridView1.DeleteRow(iCount);
                                    gridView1.AddNewRow();
                                }


                                gridView1.RefreshData();

                            }
                            else
                            {

                               
                                iCount = gridView1.FocusedRowHandle;
                                
                                gridView1.DeleteRow(iCount);
                                gridView1.RefreshData();
                            }

                            ComputeTotal();
                        }
                    }


                }

                if (e.KeyCode == Keys.Down)
                {
                    if (gridView1.IsLastRow)
                    {

                        string sItemCode = "";

                        iCount = gridView1.FocusedRowHandle;
                        sItemCode = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemCode"]).ToString();

                        if (sItemCode != "" && (txtStatus.Text == "Draft"))
                        {
                            gridView1.AddNewRow();

                            gridControl1.Select();
                            gridView1.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
                            gridView1.FocusedColumn = gridView1.VisibleColumns[1];
                            gridView1.ShowEditor();


                        }
                    }
                }
            }
            catch
            {
            }
        }

        private void btnSearchItemCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            string _ItemGuID = System.Guid.NewGuid().ToString();
            int iCount = gridView1.FocusedRowHandle;


            FND_ITM_SO _FindItemInSO = new FND_ITM_SO();

            _FindItemInSO.ConnectionString = this.ConnectionString;
            _FindItemInSO.CustomerCode = this.txtCardCode.Text;

            foreach (DataRow oRows in this.OrderLineItems.Rows)
            {
                if (oRows.RowState != DataRowState.Deleted)
                {
                    _FindItemInSO.ItemCodes.Add(oRows["ItemCode"].ToString());
                }
            }

            _FindItemInSO.ShowDialog();

            if (_FindItemInSO.ItemCode != null)
            {
                if (_FindItemInSO.ItemCode.Trim() != "")
                {

                    UoMManager oUnitMeasureManager = new UoMManager();
                    oUnitMeasureManager.ConnectionString = this.ConnectionString;
                    oUnitMeasureManager.Open();



                    BindUoM(_FindItemInSO.ItemCode, cboUnitMeasure);

                    int _unitMeasureCount = 0;
                    double _PackSize = 1;
                    string _unitMeasure = "";

                    _unitMeasureCount = cboUnitMeasure.Items.Count;

                    if (_unitMeasureCount > 0)
                    {
                        _unitMeasure = _FindItemInSO.UOM;
                        _PackSize = oUnitMeasureManager.GetPackSize(_FindItemInSO.ItemCode, _unitMeasure);
                    }

                    oUnitMeasureManager.Close();

                    gridView1.SetRowCellValue(iCount, gridView1.Columns["PriceListCode"], _FindItemInSO.PriceListCode);
                    gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemCode"], _FindItemInSO.ItemCode);
                    gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemDesc"], _FindItemInSO.Description);
                    gridView1.SetRowCellValue(iCount, gridView1.Columns["UoM"], _FindItemInSO.UOM);
                    gridView1.SetRowCellValue(iCount, gridView1.Columns["Qty"], 1);
                    gridView1.SetRowCellValue(iCount, gridView1.Columns["CQty"], _PackSize);

                    gridView1.SetRowCellValue(iCount, gridView1.Columns["UnitPrice"], _FindItemInSO.UnitPrice);

                    if (Convert.ToDouble(this.VATRate) == 0)
                    {
                        gridView1.SetRowCellValue(iCount, gridView1.Columns["UnitPrice"], _FindItemInSO.UnitPrice);

                    }
                    else
                    {

                        gridView1.SetRowCellValue(iCount, gridView1.Columns["UnitPrice"], _FindItemInSO.UnitPrice);

                    }

                    int _ZeroVAL = 0;
                    gridView1.SetRowCellValue(iCount, gridView1.Columns["DiscPrcnt"], _ZeroVAL);
                    gridView1.SetRowCellValue(iCount, gridView1.Columns["Discount"], _ZeroVAL);
                    gridView1.SetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"], _ZeroVAL);
                    bool IsChecked = false;
                    gridView1.SetRowCellValue(iCount, gridView1.Columns["IsFree"], IsChecked);
                    gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemGuID"], _ItemGuID);

                    #region Applying in Line Item Amount Computation
                    double _UNITPRICE = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["UnitPrice"]).ToString());
                    double _TOTAL_DISCOUNT = 1 * Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["Discount"]).ToString());

                    double _AMOUNT = (1 * _UNITPRICE) - _TOTAL_DISCOUNT;
                    gridView1.SetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                    gridView1.SetRowCellValue(iCount, gridView1.Columns["Amount"], _AMOUNT);
                    ComputeTotal();
                    ApplyVolumeDiscount();
                    #endregion


                }
                else
                {
                    gridView1.CancelUpdateCurrentRow();
                    if (gridView1.RowCount <= 0)
                    {
                        gridView1.AddNewRow();
                    }
                }
            }
            else
            {
                gridView1.CancelUpdateCurrentRow();
                if (gridView1.RowCount <= 0)
                {
                    gridView1.AddNewRow();
                }
            }

            _FindItemInSO.Dispose();
        }

        private void btnSearchItemCode_KeyDown(object sender, KeyEventArgs e)
        {

            this.UsedKey = e.KeyCode;


            if (e.KeyCode == Keys.Enter)
            {
                string _ItemGUID = System.Guid.NewGuid().ToString();

                DevExpress.XtraEditors.ButtonEdit oButtonEdit = (DevExpress.XtraEditors.ButtonEdit)sender;

                try
                {
                    string sItemCode = oButtonEdit.Text;
                    ItemManager oManager = new ItemManager();

                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();

                    DataTable dt = oManager.GetSlsItemByCodeWithPrice(this.DefaultPriceList, sItemCode);

                    oManager.Close();

                    if (dt.Rows.Count > 0)
                    {
                        #region If Has Rows
                        var items = from row in dt.AsEnumerable()
                                    select new
                                    {
                                        ItemCode = row["ItemCode"].ToString(),
                                        Dscription = row["Description"].ToString(),
                                        UoM = row["UNITOFMEASURE"].ToString(),
                                        UnitPrice = row["UNITPRICE"].ToString()
                                    };


                        int iCount = -1;
                        int[] oRow = gridView1.GetSelectedRows();

                        iCount = oRow[0];

                        string sVAT = this.VATCode.Trim() != "" ? this.VATCode : "N/A";
                        double _ZeroVAL = 0;
                        int iRowIndex = gridView1.FocusedRowHandle;

                        if (iRowIndex < 0)
                        {
                            iRowIndex = 0;
                        }

                        int iCountQty = 0;

                        try
                        {
                            iCountQty = Convert.ToInt32(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["Qty"]));
                        }
                        catch
                        {
                        }
                        double _PackSize = 1;
                        foreach (var oUnit in items)
                        {
                            BindUoM(oUnit.ItemCode, cboUnitMeasure);

                            int _unitMeasureCount = 0;

                            string _unitMeasure = "";
                            UoMManager oUnitMeasureManager = new UoMManager();
                            oUnitMeasureManager.ConnectionString = this.ConnectionString;
                            oUnitMeasureManager.Open();
                            _unitMeasureCount = cboUnitMeasure.Items.Count;

                            if (_unitMeasureCount > 0)
                            {
                                _unitMeasure = oUnit.UoM;
                                _PackSize = oUnitMeasureManager.GetPackSize(oUnit.ItemCode, _unitMeasure);
                            }

                            oUnitMeasureManager.Close();
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["PriceListCode"], this.DefaultPriceList);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemCode"], oUnit.ItemCode);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemDesc"], oUnit.Dscription);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["UoM"], oUnit.UoM);
                            if (iCountQty == 0)
                            {
                                gridView1.SetRowCellValue(iCount, gridView1.Columns["Qty"], 1);
                            }
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["CQty"], _PackSize);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["UnitPrice"], oUnit.UnitPrice);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["Discount"], _ZeroVAL);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["DiscPrcnt"], _ZeroVAL);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["Discount"], _ZeroVAL);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"], _ZeroVAL);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemGuID"], _ItemGUID);
                        }
                        #endregion


                        #region Applying in Line Item Amount Computation

                        double _UNITPRICE = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["UnitPrice"]).ToString());
                        double _TOTAL_DISCOUNT = (1 * _PackSize) * Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["Discount"]).ToString());

                        double _AMOUNT = ((1 * _PackSize) * _UNITPRICE) - _TOTAL_DISCOUNT;
                        gridView1.SetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                        gridView1.SetRowCellValue(iCount, gridView1.Columns["Amount"], _AMOUNT);

                        ComputeTotal();
                        ApplyVolumeDiscount();
                        #endregion


                        gridView1.FocusedColumn = gridView1.Columns["Qty"];
                        SendKeys.Send("{ENTER}");
                        return;

                    }
                    else
                    {

                        if (!(this.UsedKey == Keys.Escape))
                        {
                            string _ItemGuID = System.Guid.NewGuid().ToString();
                            int iCount = gridView1.FocusedRowHandle;
                            DevExpress.XtraEditors.ButtonEdit txt_ItemCode = (DevExpress.XtraEditors.ButtonEdit)sender;

                            FND_ITM_SO _FindItemInSO = new FND_ITM_SO();

                            _FindItemInSO.ConnectionString = this.ConnectionString;
                            _FindItemInSO.CustomerCode = this.txtCardCode.Text;

                            _FindItemInSO.FindItemCode(txt_ItemCode.Text);

                            foreach (DataRow oRows in this.OrderLineItems.Rows)
                            {
                                if (oRows.RowState != DataRowState.Deleted)
                                {
                                    _FindItemInSO.ItemCodes.Add(oRows["ItemCode"].ToString());
                                }
                            }

                            _FindItemInSO.ShowDialog();

                            if (_FindItemInSO.ItemCode != null)
                            {
                                if (_FindItemInSO.ItemCode.Trim() != "")
                                {

                                    UoMManager oUnitMeasureManager = new UoMManager();
                                    oUnitMeasureManager.ConnectionString = this.ConnectionString;
                                    oUnitMeasureManager.Open();



                                    BindUoM(_FindItemInSO.ItemCode, cboUnitMeasure);

                                    int _unitMeasureCount = 0;
                                    double _PackSize = 1;
                                    string _unitMeasure = "";

                                    _unitMeasureCount = cboUnitMeasure.Items.Count;

                                    if (_unitMeasureCount > 0)
                                    {
                                        _unitMeasure = _FindItemInSO.UOM;
                                        _PackSize = oUnitMeasureManager.GetPackSize(_FindItemInSO.ItemCode, _unitMeasure);
                                    }

                                    oUnitMeasureManager.Close();

                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["PriceListCode"], _FindItemInSO.PriceListCode);
                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemCode"], _FindItemInSO.ItemCode);
                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemDesc"], _FindItemInSO.Description);
                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["UoM"], _FindItemInSO.UOM);
                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["Qty"], 1);
                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["CQty"], _PackSize);

                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["UnitPrice"], _FindItemInSO.UnitPrice);

                                    if (Convert.ToDouble(this.VATRate) == 0)
                                    {
                                        gridView1.SetRowCellValue(iCount, gridView1.Columns["UnitPrice"], _FindItemInSO.UnitPrice);

                                    }
                                    else
                                    {

                                        gridView1.SetRowCellValue(iCount, gridView1.Columns["UnitPrice"], _FindItemInSO.UnitPrice);

                                    }

                                    int _ZeroVAL = 0;
                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["DiscPrcnt"], _ZeroVAL);
                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["Discount"], _ZeroVAL);
                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"], _ZeroVAL);
                                    bool IsChecked = false;
                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["IsFree"], IsChecked);
                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemGuID"], _ItemGuID);

                                    #region Applying in Line Item Amount Computation
                                    double _UNITPRICE = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["UnitPrice"]).ToString());
                                    double _TOTAL_DISCOUNT = 1 * Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["Discount"]).ToString());

                                    double _AMOUNT = (1 * _UNITPRICE) - _TOTAL_DISCOUNT;
                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["Amount"], _AMOUNT);
                                    ComputeTotal();
                                    ApplyVolumeDiscount();
                                    #endregion


                                }
                                else
                                {
                                    gridView1.CancelUpdateCurrentRow();
                                    if (gridView1.RowCount <= 0)
                                    {
                                        gridView1.AddNewRow();
                                    }
                                }
                            }
                            else
                            {
                                gridView1.CancelUpdateCurrentRow();
                                if (gridView1.RowCount <= 0)
                                {
                                    gridView1.AddNewRow();
                                }
                            }

                            _FindItemInSO.Dispose();
                            this.UsedKey = Keys.None;
                        }
                        else
                        {
                            this.UsedKey = Keys.None;
                        }
                    }
                }
                catch
                {
                }

            }



            if (e.KeyCode == Keys.Tab)
            {
                string _ItemGUID = System.Guid.NewGuid().ToString();

                DevExpress.XtraEditors.ButtonEdit oButtonEdit = (DevExpress.XtraEditors.ButtonEdit)sender;

                try
                {
                    string sItemCode = oButtonEdit.Text;
                    ItemManager oManager = new ItemManager();

                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();

                    DataTable dt = oManager.GetSlsItemByCodeWithPrice(this.DefaultPriceList, sItemCode);

                    oManager.Close();

                    if (dt.Rows.Count > 0)
                    {
                        #region If Has Rows
                        var items = from row in dt.AsEnumerable()
                                    select new
                                    {
                                        ItemCode = row["ItemCode"].ToString(),
                                        Dscription = row["Description"].ToString(),
                                        UoM = row["UNITOFMEASURE"].ToString(),
                                        UnitPrice = row["UNITPRICE"].ToString()
                                    };


                        int iCount = -1;
                        int[] oRow = gridView1.GetSelectedRows();

                        iCount = oRow[0];

                        string sVAT = this.VATCode.Trim() != "" ? this.VATCode : "N/A";
                        double _ZeroVAL = 0;
                        int iRowIndex = gridView1.FocusedRowHandle;

                        if (iRowIndex < 0)
                        {
                            iRowIndex = 0;
                        }

                        int iCountQty = 0;

                        try
                        {
                            iCountQty = Convert.ToInt32(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["Qty"]));
                        }
                        catch
                        {
                        }
                        double _PackSize = 1;
                        foreach (var oUnit in items)
                        {
                            BindUoM(oUnit.ItemCode, cboUnitMeasure);

                            int _unitMeasureCount = 0;

                            string _unitMeasure = "";
                            UoMManager oUnitMeasureManager = new UoMManager();
                            oUnitMeasureManager.ConnectionString = this.ConnectionString;
                            oUnitMeasureManager.Open();
                            _unitMeasureCount = cboUnitMeasure.Items.Count;

                            if (_unitMeasureCount > 0)
                            {
                                _unitMeasure = oUnit.UoM;
                                _PackSize = oUnitMeasureManager.GetPackSize(oUnit.ItemCode, _unitMeasure);
                            }

                            oUnitMeasureManager.Close();
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["PriceListCode"], this.DefaultPriceList);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemCode"], oUnit.ItemCode);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemDesc"], oUnit.Dscription);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["UoM"], oUnit.UoM);
                            if (iCountQty == 0)
                            {
                                gridView1.SetRowCellValue(iCount, gridView1.Columns["Qty"], 1);
                            }
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["CQty"], _PackSize);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["UnitPrice"], oUnit.UnitPrice);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["Discount"], _ZeroVAL);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["DiscPrcnt"], _ZeroVAL);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["Discount"], _ZeroVAL);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"], _ZeroVAL);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemGuID"], _ItemGUID);
                        }
                        #endregion


                        #region Applying in Line Item Amount Computation

                        double _UNITPRICE = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["UnitPrice"]).ToString());
                        double _TOTAL_DISCOUNT = (1 * _PackSize) * Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["Discount"]).ToString());

                        double _AMOUNT = ((1 * _PackSize) * _UNITPRICE) - _TOTAL_DISCOUNT;
                        gridView1.SetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                        gridView1.SetRowCellValue(iCount, gridView1.Columns["Amount"], _AMOUNT);

                        ComputeTotal();
                        ApplyVolumeDiscount();
                        #endregion


                        gridView1.FocusedColumn = gridView1.Columns["UoM"];
                        SendKeys.Send("{ENTER}");
                        return;

                    }
                    else
                    {

                        if (!(this.UsedKey == Keys.Escape))
                        {

                            string _ItemGuID = System.Guid.NewGuid().ToString();
                            int iCount = gridView1.FocusedRowHandle;
                            DevExpress.XtraEditors.ButtonEdit txt_ItemCode = (DevExpress.XtraEditors.ButtonEdit)sender;

                            FND_ITM_SO _FindItemInSO = new FND_ITM_SO();

                            _FindItemInSO.ConnectionString = this.ConnectionString;
                            _FindItemInSO.CustomerCode = this.txtCardCode.Text;

                            _FindItemInSO.FindItemCode(txt_ItemCode.Text);

                            foreach (DataRow oRows in this.OrderLineItems.Rows)
                            {
                                if (oRows.RowState != DataRowState.Deleted)
                                {
                                    _FindItemInSO.ItemCodes.Add(oRows["ItemCode"].ToString());
                                }
                            }

                            _FindItemInSO.ShowDialog();

                            if (_FindItemInSO.ItemCode != null)
                            {
                                if (_FindItemInSO.ItemCode.Trim() != "")
                                {

                                    UoMManager oUnitMeasureManager = new UoMManager();
                                    oUnitMeasureManager.ConnectionString = this.ConnectionString;
                                    oUnitMeasureManager.Open();



                                    BindUoM(_FindItemInSO.ItemCode, cboUnitMeasure);

                                    int _unitMeasureCount = 0;
                                    double _PackSize = 1;
                                    string _unitMeasure = "";

                                    _unitMeasureCount = cboUnitMeasure.Items.Count;

                                    if (_unitMeasureCount > 0)
                                    {
                                        _unitMeasure = _FindItemInSO.UOM;
                                        _PackSize = oUnitMeasureManager.GetPackSize(_FindItemInSO.ItemCode, _unitMeasure);
                                    }

                                    oUnitMeasureManager.Close();
                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["PriceListCode"], _FindItemInSO.PriceListCode);
                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemCode"], _FindItemInSO.ItemCode);
                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemDesc"], _FindItemInSO.Description);
                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["UoM"], _FindItemInSO.UOM);
                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["Qty"], 1);
                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["CQty"], _PackSize);

                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["UnitPrice"], _FindItemInSO.UnitPrice);

                                    if (Convert.ToDouble(this.VATRate) == 0)
                                    {
                                        gridView1.SetRowCellValue(iCount, gridView1.Columns["UnitPrice"], _FindItemInSO.UnitPrice);

                                    }
                                    else
                                    {

                                        gridView1.SetRowCellValue(iCount, gridView1.Columns["UnitPrice"], _FindItemInSO.UnitPrice);

                                    }

                                    int _ZeroVAL = 0;
                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["DiscPrcnt"], _ZeroVAL);
                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["Discount"], _ZeroVAL);
                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"], _ZeroVAL);
                                    bool IsChecked = false;
                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["IsFree"], IsChecked);
                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemGuID"], _ItemGuID);

                                    #region Applying in Line Item Amount Computation
                                    double _UNITPRICE = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["UnitPrice"]).ToString());
                                    double _TOTAL_DISCOUNT = 1 * Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["Discount"]).ToString());

                                    double _AMOUNT = (1 * _UNITPRICE) - _TOTAL_DISCOUNT;
                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                                    gridView1.SetRowCellValue(iCount, gridView1.Columns["Amount"], _AMOUNT);
                                    ComputeTotal();
                                    ApplyVolumeDiscount();
                                    #endregion


                                }
                                else
                                {
                                    gridView1.CancelUpdateCurrentRow();
                                    if (gridView1.RowCount <= 0)
                                    {
                                        gridView1.AddNewRow();
                                    }
                                }
                            }
                            else
                            {
                                gridView1.CancelUpdateCurrentRow();
                                if (gridView1.RowCount <= 0)
                                {
                                    gridView1.AddNewRow();
                                }
                            }

                            _FindItemInSO.Dispose();
                            this.UsedKey = Keys.None;
                        }
                        else
                        {
                            this.UsedKey = Keys.None;
                        }
                    }
                }
                catch
                {
                }

            }
        }

        private void txtQty_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    int iCount = -1;
                    int[] oRow = gridView1.GetSelectedRows();
                    iCount = oRow[0];

                    DevExpress.XtraEditors.TextEdit oTextQty = (DevExpress.XtraEditors.TextEdit)sender;

                    double _QUANTITY = Convert.ToDouble(oTextQty.Text);
                    string _ITEMCODE = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemCode"]).ToString();
                    double _UNITPRICE = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["UnitPrice"]).ToString());
                    double _TOTAL_DISCOUNT = _QUANTITY * Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["Discount"]).ToString());

                    double _AMOUNT = (_QUANTITY * _UNITPRICE) - _TOTAL_DISCOUNT;
                    gridView1.SetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                    gridView1.SetRowCellValue(iCount, gridView1.Columns["Amount"], _AMOUNT);
                    bool IsChecked = false;
                    gridView1.SetRowCellValue(iCount, gridView1.Columns["IsFree"], IsChecked);
                    ComputeTotal();
                    ApplyVolumeDiscount();
                }
                catch
                {
                }
            }
        }

        private void txtLineDiscount_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                int iCount = -1;
                int[] oRow = gridView1.GetSelectedRows();

                iCount = oRow[0];
                DevExpress.XtraEditors.TextEdit oTxtLineDiscount = (DevExpress.XtraEditors.TextEdit)sender;

                double _lineDiscount = Convert.ToDouble(oTxtLineDiscount.Text);
                double _UnitPrice = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["UnitPrice"]).ToString());
                double _Qty = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["Qty"]).ToString());
                double _Percentage = 0;

                _Percentage = _lineDiscount / _UnitPrice;

                gridView1.SetRowCellValue(iCount, gridView1.Columns["DiscPrcnt"], (_Percentage * 100));
                gridView1.SetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"], _Qty * _lineDiscount);

                double _TotalDiscount = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"]).ToString());

                double _Amount = (_Qty * _UnitPrice) - _TotalDiscount;

                gridView1.SetRowCellValue(iCount, gridView1.Columns["Amount"], _Amount);

                ComputeTotal();

            }
        }

        private void txtLineDiscPercent_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                int iCount = -1;
                int[] oRow = gridView1.GetSelectedRows();

                iCount = oRow[0];
                DevExpress.XtraEditors.TextEdit oTxtDiscPrcnt = (DevExpress.XtraEditors.TextEdit)sender;

                double _discPrcnt = Convert.ToDouble(oTxtDiscPrcnt.Text);
                double _UnitPrice = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["UnitPrice"]).ToString());
                double _Qty = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["Qty"]).ToString());

                double _LineDiscount = _UnitPrice * (_discPrcnt / 100);
                double _TotalDiscount = _Qty * _LineDiscount;

                gridView1.SetRowCellValue(iCount, gridView1.Columns["Discount"], _LineDiscount);
                gridView1.SetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"], _TotalDiscount);

                double _Amount = (_Qty * _UnitPrice) - _TotalDiscount;

                gridView1.SetRowCellValue(iCount, gridView1.Columns["Amount"], _Amount);

                ComputeTotal();
                ApplyVolumeDiscount();
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            ConsignmentManager oManager = new ConsignmentManager();
            ConsignmentUnit oUnit = new ConsignmentUnit();


            if (txtCardCode.Text != "")
            {

                RemoveBlankLastRowFirst();
                if (IsComplete() == true)
                {
                    if (btnAdd.Text != "Update")
                    {
                        #region Header Sales Order

                        txtDocumentNumber.Text = GetNewSeries();
                        oUnit.DocumentNumber = txtDocumentNumber.Text;
                        oUnit.DocumentStatus = txtStatus.Text;
                        oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                        oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                        oUnit.DocDate = (DateTime)dtDocDate.EditValue;

                        oUnit.StoreCode = txtStoreCode.Text;
                        oUnit.CardCode = txtCardCode.Text;
                        oUnit.CardName = txtCardName.Text;
                        oUnit.ContactPerson = txtContactPerson.Text;
                        oUnit.PaymentTerms = txtPaymentTerms.Text;
                        oUnit.Reference = txtReference.Text;
                        oUnit.ShipTo = txtShipTo.Text;
                        oUnit.BillTo = txtBillTo.Text;
                        oUnit.Location = cboLocation.EditValue.ToString();
                     

                        oUnit.Destination = cboDestination.EditValue.ToString();
                  
                        if (cboSalesman.EditValue != null)
                        {
                            oUnit.SalesMan = cboSalesman.EditValue.ToString();
                        }
                        else
                        {
                            oUnit.SalesMan = "";
                        }

                        oUnit.Remarks = txtRemarks.Text;
                        if (this.VATCode != null)
                        {
                            oUnit.TaxCode = this.VATCode.ToString();
                            oUnit.TaxRate = Convert.ToDouble(this.VATRate.ToString());
                        }
                        else
                        {
                            oUnit.TaxCode = "NON-VAT";
                            oUnit.TaxRate = 0;
                        }
                        if (oUnit.TaxCode != "NON-VAT")
                        {
                            oUnit.IsVATInclusive = this.IsInclusive == true ? "Y" : "N";
                        }
                        else
                        {
                            oUnit.IsVATInclusive = "N/A";
                        }



                        oUnit.GrossAmnt = Convert.ToDouble(txtGrossAmount.Text.Replace(",", "").ToString());
                        oUnit.VATAmt = Convert.ToDouble(txtVAT.Text.Replace(",", "").ToString());
                        oUnit.TotalLineDisc = Convert.ToDouble(txtTotalLineDiscount.Text.Replace(",", "").ToString());

                        oUnit.Discount1 = txtDisc1.Text;
                        oUnit.Discount2 = txtDisc2.Text;
                        oUnit.Discount3 = txtDisc3.Text;
                        oUnit.Discount4 = txtDisc4.Text;

                        oUnit.TotalDiscount = Convert.ToDouble(txtTotalDiscount.Text.Replace(",", "").ToString());
                        oUnit.NetAmount = Convert.ToDouble(txtNetAmt.Text.Replace(",", "").ToString());

                        oUnit.DateCreated = System.DateTime.Now;
                        oUnit.CreatedBy = this.ActiveUserID;
                        oUnit.DateModified = System.DateTime.Now;
                        oUnit.ModifiedBy = this.ActiveUserID;

                        #endregion

                        oUnit.LineItems = this.OrderLineItems;

                        #region Adding Part
                        oManager.ConnectionString = this.ConnectionString;
                        oManager.Open();
                        oManager.AddOrder(oUnit);
                        oManager.Close();
                        #endregion

                        btnAdd.Text = "Update";

                        MainMenu oForm = (MainMenu)this.MdiParent;

                        oForm.ErrMsg.ImageIndex = 8;
                        oForm.ErrMsg.Caption = "Saving document is successful!!!";
                        oForm.timer1.Enabled = true;
                        //MessageBox.Show(, "Sales Order", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {

                        #region Header Sales Order

                        oUnit.DocumentNumber = txtDocumentNumber.Text;
                        oUnit.DocumentStatus = txtStatus.Text;
                        oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                        oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                        oUnit.DocDate = (DateTime)dtDocDate.EditValue;

                        oUnit.StoreCode = txtStoreCode.Text;
                        oUnit.CardCode = txtCardCode.Text;
                        oUnit.CardName = txtCardName.Text;
                        oUnit.ContactPerson = txtContactPerson.Text;
                        oUnit.PaymentTerms = txtPaymentTerms.Text;
                        oUnit.Reference = txtReference.Text;
                        oUnit.ShipTo = txtShipTo.Text;
                        oUnit.BillTo = txtBillTo.Text;
                        oUnit.Location = cboLocation.EditValue.ToString();
                        if (cboDestination.EditValue == null)
                        {
                            MessageBox.Show("Please select destination!!!", "Destination", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }

                        oUnit.Destination = cboDestination.EditValue.ToString();

                        if (cboSalesman.EditValue != null)
                        {
                            oUnit.SalesMan = cboSalesman.EditValue.ToString();
                        }
                        else
                        {
                            oUnit.SalesMan = "";
                        }

                        oUnit.Remarks = txtRemarks.Text;

                        oUnit.TaxCode = this.VATCode.ToString();
                        oUnit.TaxRate = Convert.ToDouble(this.VATRate.ToString());
                        if (oUnit.TaxCode != "NON-VAT")
                        {
                            oUnit.IsVATInclusive = this.IsInclusive == true ? "Y" : "N";
                        }
                        else
                        {
                            oUnit.IsVATInclusive = "N/A";
                        }



                        oUnit.GrossAmnt = Convert.ToDouble(txtGrossAmount.Text.Replace(",", "").ToString());
                        oUnit.VATAmt = Convert.ToDouble(txtVAT.Text.Replace(",", "").ToString());
                        oUnit.TotalLineDisc = Convert.ToDouble(txtTotalLineDiscount.Text.Replace(",", "").ToString());

                        oUnit.Discount1 = txtDisc1.Text;
                        oUnit.Discount2 = txtDisc2.Text;
                        oUnit.Discount3 = txtDisc3.Text;
                        oUnit.Discount4 = txtDisc4.Text;

                        oUnit.TotalDiscount = Convert.ToDouble(txtTotalDiscount.Text.Replace(",", "").ToString());
                        oUnit.NetAmount = Convert.ToDouble(txtNetAmt.Text.Replace(",", "").ToString());
                        oUnit.DateModified = System.DateTime.Now;
                        oUnit.ModifiedBy = this.ActiveUserID;

                        #endregion

                        oUnit.LineItems = this.OrderLineItems;

                        #region Updating Portion
                        oManager.ConnectionString = this.ConnectionString;
                        oManager.Open();
                        oManager.UpdateOrder(oUnit);
                        oManager.Close();
                        #endregion

                        MainMenu oForm = (MainMenu)this.MdiParent;

                        oForm.ErrMsg.ImageIndex = 8;
                        oForm.ErrMsg.Caption = "Updating document is successful!!!";
                        oForm.timer1.Enabled = true;
                        //MessageBox.Show("Updating document is successful!!!", "Sales Order", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    MainMenu oForm = (MainMenu)this.MdiParent;

                    oForm.ErrMsg.ImageIndex = 6;
                    oForm.ErrMsg.Caption = "Please complete the information before saving!!!";
                    oForm.timer1.Enabled = true;


                    if (gridView1.RowCount == 0)
                    {
                        gridView1.AddNewRow();
                        gridView1.Focus();

                        SendKeys.Send("{DOWN}");
                    }
                    
                    
                    //MessageBox.Show("Please complete the information before saving!!!", "Sales Order", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                MainMenu oForm = (MainMenu)this.MdiParent;

                oForm.ErrMsg.ImageIndex = 6;
                oForm.ErrMsg.Caption = "Please complete the information before saving!!!";
                oForm.timer1.Enabled = true;

                if (gridView1.RowCount == 0)
                {
                    gridView1.AddNewRow();
                    gridView1.Focus();

                    SendKeys.Send("{DOWN}");
                }
                //MessageBox.Show("Please complete the information before saving!!!", "Sales Order", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        private void txtDiscount_EditValueChanged(object sender, EventArgs e)
        {
            if (txtDisc1.Text.Trim() != "0%" && txtDisc1.Text.Trim() != "" && txtDisc1.Text.Trim() != ".0000%" && txtDisc1.Text.Trim() != "0" && txtDisc1.Text.Trim() != ".0000")
            {
                txtDisc2.Enabled = true;
            }
            else
            {
                txtDisc2.Enabled = false;
                txtDisc2.Text = "0%";
                txtDisc3.Enabled = false;
                txtDisc3.Text = "0%";
                txtDisc4.Enabled = false;
                txtDisc4.Text = "0%";
            }
        }

        private void txtDisc2_EditValueChanged(object sender, EventArgs e)
        {
            if (txtDisc2.Text.Trim() != "0%" && txtDisc2.Text.Trim() != "" && txtDisc2.Text.Trim() != ".0000%" && txtDisc2.Text.Trim() != "0" && txtDisc2.Text.Trim() != ".0000")
            {
                txtDisc3.Enabled = true;
            }
            else
            {
                txtDisc3.Enabled = false;
                txtDisc3.Text = "0%";
                txtDisc4.Enabled = false;
                txtDisc4.Text = "0%";
            }
        }

        private void txtDisc3_EditValueChanged(object sender, EventArgs e)
        {
            if (txtDisc3.Text.Trim() != "0%" && txtDisc3.Text.Trim() != "" && txtDisc3.Text.Trim() != ".0000%" && txtDisc3.Text.Trim() != "0" && txtDisc3.Text.Trim() != ".0000")
            {
                txtDisc4.Enabled = true;
            }
            else
            {
                txtDisc4.Enabled = false;
                txtDisc4.Text = "0%";
            }
        }

        private void txtDisc4_EditValueChanged(object sender, EventArgs e)
        {
            if (txtDisc3.Text.Trim() != "0%" && txtDisc3.Text.Trim() != "" && txtDisc3.Text.Trim() != ".0000%" && txtDisc3.Text.Trim() != "0" && txtDisc3.Text.Trim() != ".0000")
            {
                txtDisc4.Enabled = true;
            }
            else
            {
                txtDisc4.Enabled = false;
                txtDisc4.Text = "0%";
            }
        }

        private void txtDiscount_Leave(object sender, EventArgs e)
        {
            try
            {
                double iCheck = Convert.ToDouble(txtDisc1.Text.Replace("%", ""));

                if (iCheck > 0)
                {
                    txtDisc1.Text = string.Format("{0:###.0000}", txtDisc1.Text.Trim()) + "%";
                }
                else
                {
                    txtDisc1.Text = "0%";
                }
            }
            catch
            {
                MainMenu oForm = (MainMenu)this.MdiParent;

                oForm.ErrMsg.ImageIndex = 6;
                oForm.ErrMsg.Caption = "Doesn't allow character please insert number only!!!";
                oForm.timer1.Enabled = true;
                //MessageBox.Show("Doesn't allow character please insert number only!!!", "Error Input", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtDisc1.Text = "0%";
            }
        }

        private void txtDisc2_Leave(object sender, EventArgs e)
        {
            try
            {
                double iCheck = Convert.ToDouble(txtDisc2.Text.Replace("%", ""));

                if (iCheck > 0)
                {
                    txtDisc2.Text = string.Format("{0:###.0000}", txtDisc2.Text.Trim()) + "%";
                }
                else
                {
                    txtDisc2.Text = "0%";
                }
            }
            catch
            {
                MainMenu oForm = (MainMenu)this.MdiParent;

                oForm.ErrMsg.ImageIndex = 6;
                oForm.ErrMsg.Caption = "Doesn't allow character please insert number only!!!";
                oForm.timer1.Enabled = true;
                //MessageBox.Show("Doesn't allow character please insert number only!!!", "Error Input", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtDisc2.Text = "0%";
            }
        }

        private void txtDisc3_Leave(object sender, EventArgs e)
        {
            try
            {
                double iCheck = Convert.ToDouble(txtDisc3.Text.Replace("%", ""));

                if (iCheck > 0)
                {
                    txtDisc3.Text = string.Format("{0:###.0000}", txtDisc3.Text.Trim()) + "%";
                }
                else
                {
                    txtDisc3.Text = "0%";
                }
            }
            catch
            {
                MainMenu oForm = (MainMenu)this.MdiParent;

                oForm.ErrMsg.ImageIndex = 6;
                oForm.ErrMsg.Caption = "Doesn't allow character please insert number only!!!";
                oForm.timer1.Enabled = true;
                //MessageBox.Show("Doesn't allow character please insert number only!!!", "Error Input", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtDisc3.Text = "0%";
            }
        }

        private void txtDisc4_Leave(object sender, EventArgs e)
        {
            try
            {
                double iCheck = Convert.ToDouble(txtDisc4.Text.Replace("%", ""));

                if (iCheck > 0)
                {
                    txtDisc4.Text = string.Format("{0:###.0000}", txtDisc4.Text.Trim()) + "%";
                }
                else
                {
                    txtDisc4.Text = "0%";
                }
            }
            catch
            {
                MainMenu oForm = (MainMenu)this.MdiParent;

                oForm.ErrMsg.ImageIndex = 6;
                oForm.ErrMsg.Caption = "Doesn't allow character please insert number only!!!";
                oForm.timer1.Enabled = true;
                //MessageBox.Show("Doesn't allow character please insert number only!!!", "Error Input", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtDisc4.Text = "0%";
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtQty_Leave(object sender, EventArgs e)
        {

            try
            {
                int iCount = -1;
                int[] oRow = gridView1.GetSelectedRows();
                iCount = oRow[0];

                DevExpress.XtraEditors.TextEdit oTextQty = (DevExpress.XtraEditors.TextEdit)sender;

                double _QUANTITY = Convert.ToDouble(oTextQty.Text);
                double _CQUANTITY = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["CQty"]).ToString());
                string _ITEMCODE = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemCode"]).ToString();
                double _UNITPRICE = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["UnitPrice"]).ToString());
                double _TOTAL_DISCOUNT = (_QUANTITY * _CQUANTITY) * Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["Discount"]).ToString());

                double _AMOUNT = ((_QUANTITY * _CQUANTITY) * _UNITPRICE) - _TOTAL_DISCOUNT;
                gridView1.SetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                gridView1.SetRowCellValue(iCount, gridView1.Columns["Amount"], _AMOUNT);
                bool IsChecked = false;
                gridView1.SetRowCellValue(iCount, gridView1.Columns["IsFree"], IsChecked);
                ComputeTotal();
                ApplyVolumeDiscount();
            }
            catch
            {
            }
        }

        private void gridView1_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            ComputeTotal();
        }

        private void xtraScrollableControl1_Click(object sender, EventArgs e)
        {

        }

        private void txtDiscount_Enter(object sender, EventArgs e)
        {
            txtDisc1.Text = txtDisc1.Text.Replace("%", "");
        }

        private void txtDisc2_Enter(object sender, EventArgs e)
        {
            txtDisc2.Text = txtDisc2.Text.Replace("%", "");
        }

        private void txtDisc3_Enter(object sender, EventArgs e)
        {
            txtDisc3.Text = txtDisc3.Text.Replace("%", "");
        }

        private void txtDisc4_Enter(object sender, EventArgs e)
        {
            txtDisc4.Text = txtDisc4.Text.Replace("%", "");
        }

        private void txtDiscount_Validated(object sender, EventArgs e)
        {
            ApplyVolumeDiscount();
        }

        private void txtDisc2_Validated(object sender, EventArgs e)
        {
            ApplyVolumeDiscount();
        }

        private void txtDisc3_Validated(object sender, EventArgs e)
        {
            ApplyVolumeDiscount();
        }

        private void txtDisc4_Validated(object sender, EventArgs e)
        {
            ApplyVolumeDiscount();
        }

        private void chkFree_CheckedChanged(object sender, EventArgs e)
        {
            int iCount = -1;
            int[] oRow = gridView1.GetSelectedRows();

            iCount = oRow[0];
            DevExpress.XtraEditors.CheckEdit oCheckBox = (DevExpress.XtraEditors.CheckEdit)sender;

            bool IsChecked = oCheckBox.Checked;
            int _ZeroVAL = 0;
            gridView1.SetRowCellValue(iCount, gridView1.Columns["IsFree"], IsChecked);
            if (IsChecked == true)
            {

                gridView1.SetRowCellValue(iCount, gridView1.Columns["DiscPrcnt"], _ZeroVAL);
                gridView1.SetRowCellValue(iCount, gridView1.Columns["Discount"], _ZeroVAL);
                gridView1.SetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"], _ZeroVAL);

                gridView1.SetRowCellValue(iCount, gridView1.Columns["Amount"], _ZeroVAL);
            }
            else
            {
                string sItemCode = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemCode"]).ToString();
                double dNetPrice = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["UnitPrice"]).ToString());
                double iQty = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["Qty"]).ToString());
                double CQty = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["CQty"]).ToString());

                gridView1.SetRowCellValue(iCount, gridView1.Columns["DiscPrcnt"], _ZeroVAL);
                gridView1.SetRowCellValue(iCount, gridView1.Columns["Discount"], _ZeroVAL);
                gridView1.SetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"], _ZeroVAL);
                gridView1.SetRowCellValue(iCount, gridView1.Columns["Amount"], (iQty * CQty) * Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["UnitPrice"])));
            }

            //OrderLineItems.AcceptChanges();
            ComputeTotal();
            ApplyVolumeDiscount();
        }

        #endregion

        private void txtStatus_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (txtDocumentNumber.Text != "##########")
            {
                if (txtStatus.Text == "Draft")
                {
                    if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.OK)
                    {
                        PostOrder(txtDocumentNumber.Text);
                    }

                    if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Close)
                    {
                        CancelOrder(txtDocumentNumber.Text);
                    }
                }
                else
                {
                    if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Close)
                    {
                        CloseOrder(txtDocumentNumber.Text);
                    }
                }
            }

        }

        private void txtStatus_EditValueChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "Draft")
            {
                txtStatus.Properties.Buttons[0].Visible = true;
                txtStatus.Properties.Buttons[1].Visible = true;
                EnableControls();
                btnCopyToDelivery.Visible = false;
                btnCreateTransfer.Visible = false;

                copyToolStripMenuItem.Enabled = false;

                duplicateToolMenu.Enabled = true;
                insertNewRowToolStripMenuItem.Enabled = true;
                addRowToolStripMenuItem.Enabled = true;
                deleteRowToolStripMenuItem.Enabled = true;
            }
            if (txtStatus.Text == "Canceled" || txtStatus.Text == "Closed")
            {
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = false;
                DisableControls();
                btnCopyToDelivery.Visible = false;
                btnCreateTransfer.Visible = false;
                copyToolStripMenuItem.Enabled = false;

                duplicateToolMenu.Enabled = false;
                insertNewRowToolStripMenuItem.Enabled = false;
                addRowToolStripMenuItem.Enabled = false;
                deleteRowToolStripMenuItem.Enabled = false;
            }

            if (txtStatus.Text == "Posted")
            {
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = true;
                DisableControls();
                btnCopyToDelivery.Visible = true;
                btnCreateTransfer.Visible = true;
                copyToolStripMenuItem.Enabled = true;

                duplicateToolMenu.Enabled = false;
                insertNewRowToolStripMenuItem.Enabled = false;
                addRowToolStripMenuItem.Enabled = false;
                deleteRowToolStripMenuItem.Enabled = false;
            }

            if (txtStatus.Text == "Open")
            {
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = true;
                DisableControls();
                btnCopyToDelivery.Visible = true;
                btnCreateTransfer.Visible = true;
                copyToolStripMenuItem.Enabled = true;
                duplicateToolMenu.Enabled = false;
                insertNewRowToolStripMenuItem.Enabled = false;
                addRowToolStripMenuItem.Enabled = false;
                deleteRowToolStripMenuItem.Enabled = false;
            }
        }

        private void dtPostDate_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                dtDeliveryDate.Properties.MinValue = (DateTime)dtPostDate.EditValue;
            }
            catch
            {
            }
        }

        private void txtUnitPrice_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    int iCount = -1;
                    int[] oRow = gridView1.GetSelectedRows();
                    iCount = oRow[0];

                    DevExpress.XtraEditors.TextEdit oTextPrice = (DevExpress.XtraEditors.TextEdit)sender;

                    double _QUANTITY = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["Qty"]).ToString());
                    double _CQUANTITY = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["CQty"]).ToString());
                    string _ITEMCODE = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemCode"]).ToString();
                    double _UNITPRICE = Convert.ToDouble(oTextPrice.EditValue);
                    double _TOTAL_DISCOUNT = (_QUANTITY * _CQUANTITY) * Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["Discount"]).ToString());

                    double _AMOUNT = ((_QUANTITY * _CQUANTITY) * _UNITPRICE) - _TOTAL_DISCOUNT;
                    gridView1.SetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                    gridView1.SetRowCellValue(iCount, gridView1.Columns["Amount"], _AMOUNT);
                    bool IsChecked = false;
                    gridView1.SetRowCellValue(iCount, gridView1.Columns["IsFree"], IsChecked);
                    ComputeTotal();
                    ApplyVolumeDiscount();
                }
                catch
                {
                }
            }
        }

        private void txtLineDiscPercent_Leave(object sender, EventArgs e)
        {
            try
            {
                int iCount = -1;
                int[] oRow = gridView1.GetSelectedRows();

                iCount = oRow[0];
                DevExpress.XtraEditors.TextEdit oTxtDiscPrcnt = (DevExpress.XtraEditors.TextEdit)sender;

                double _discPrcnt = Convert.ToDouble(oTxtDiscPrcnt.Text);
                double _UnitPrice = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["UnitPrice"]).ToString());
                double _Qty = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["Qty"]).ToString());
                double _CQty = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["CQty"]).ToString());

                double _LineDiscount = _UnitPrice * (_discPrcnt / 100);
                double _TotalDiscount = (_Qty * _CQty) * _LineDiscount;

                gridView1.SetRowCellValue(iCount, gridView1.Columns["Discount"], _LineDiscount);
                gridView1.SetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"], _TotalDiscount);

                double _Amount = ((_Qty * _CQty) * _UnitPrice) - _TotalDiscount;

                gridView1.SetRowCellValue(iCount, gridView1.Columns["Amount"], _Amount);

                ComputeTotal();
                ApplyVolumeDiscount();
            }
            catch
            {
            }
        }

        private void txtCardCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AddressBookManager oManager = new AddressBookManager();
                TaxManager oTxManager = new TaxManager();
                DataTable _TABLE = new DataTable();

                try
                {

                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();

                    _TABLE = oManager.GetByBPCode(txtCardCode.Text, "Customer");

                    oManager.Close();

                    int iCount = _TABLE.Rows.Count;

                    if (iCount == 0)
                    {
                        #region if no data return during enter
                        FND_BP _SearchBP = new FND_BP();

                        AddressBookManager oBPManager = new AddressBookManager();

                        try
                        {
                            _SearchBP.ConnectionString = this.ConnectionString;
                            _SearchBP.BusinessPartnerType = "Customer";
                            _SearchBP.SetSearchByBPCode(txtCardCode.Text);

                            _SearchBP.ShowDialog();

                            txtStoreCode.Text = _SearchBP.StoreCode;
                            txtCardCode.Text = _SearchBP.CardCode;
                            txtCardName.Text = _SearchBP.CardName;
                            txtBillTo.Text = _SearchBP.Address;
                            txtPaymentTerms.Text = _SearchBP.PaymentTerm.ToString();
                            txtContactPerson.Text = _SearchBP.ContactPerson;
                            this.DefaultPriceList = _SearchBP.PriceList;
                            this.VATCode = _SearchBP.VATCode;
                            try
                            {
                                txtDisc1.Text = _SearchBP.Discount1.ToString() + "%";
                                txtDisc2.Text = _SearchBP.Discount2.ToString() + "%";
                                txtDisc3.Text = _SearchBP.Discount3.ToString() + "%";
                                txtDisc4.Text = _SearchBP.Discount4.ToString() + "%";
                            }
                            catch
                            {
                            }


                            oTxManager.ConnectionString = this.ConnectionString;
                            oTxManager.Open();


                            this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();

                            this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;



                            oTxManager.Close();

                            if (_SearchBP.BuyerSalesMan != "")
                            {
                                cboSalesman.EditValue = _SearchBP.BuyerSalesMan;
                            }

                            _SearchBP.Dispose();
                        }
                        catch
                        {
                        }
                        #endregion
                        return;
                    }

                    DataRow oRow = _TABLE.Rows[0];

                    txtStoreCode.Text = oRow["StoreCode"].ToString();
                    txtCardCode.Text = oRow["BPCode"].ToString();
                    txtCardName.Text = oRow["BPName"].ToString();
                    txtBillTo.Text = oRow["Address"].ToString();
                    txtPaymentTerms.Text = oRow["PaymentTerm"].ToString();
                    txtContactPerson.Text = oRow["ContactPerson"].ToString(); ;
                    this.DefaultPriceList = oRow["PriceList"].ToString(); ;
                    this.VATCode = oRow["VATCode"].ToString();
                    try
                    {
                        txtDisc1.Text = oRow["Disc1"].ToString() + "%";
                        txtDisc2.Text = oRow["Disc2"].ToString() + "%";
                        txtDisc3.Text = oRow["Disc3"].ToString() + "%";
                        txtDisc4.Text = oRow["Disc4"].ToString() + "%";
                    }
                    catch
                    {
                    }

                    oTxManager.ConnectionString = this.ConnectionString;
                    oTxManager.Open();


                    this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();

                    this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;


                    oTxManager.Close();

                    if (oRow["SMCODE"].ToString() != "")
                    {
                        cboSalesman.EditValue = oRow["SMCODE"].ToString();
                    }
                }
                catch
                {
                }
            }
        }

        private void SalesOrder_Shown(object sender, EventArgs e)
        {
            gridControl1.Select();
            gridView1.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
            gridView1.FocusedColumn = gridView1.Columns["ItemCode"];
            gridView1.ShowEditor();


            txtCardCode.Focus();

            string _USR_AUTHORIZATION = ApplyAuthorization();
            if (_USR_AUTHORIZATION == "No Access")
            {
                btnCancel_Click(sender, e);
            }
        }

        private void btnCopyToDelivery_Click(object sender, EventArgs e)
        {
            SalesDelivery oForm = new SalesDelivery();

            oForm.ConnectionString = this.ConnectionString;
            oForm.ActiveUserID = this.ActiveUserID;
            oForm.DefaultWarehouse = this.DefaultWarehouse;
            oForm.IsMultipleWarehouse = this.IsMultipleWarehouse;

            oForm.MdiParent = this.MdiParent;
            oForm.CopyConsignmentToDelivery(txtDocumentNumber.Text);
            oForm.Show();


        }

        private void txtQty_EditValueChanged(object sender, EventArgs e)
        {
            DevExpress.XtraEditors.TextEdit textQty = (DevExpress.XtraEditors.TextEdit)sender;
            int iQty = 0;
            try
            {
                iQty = Convert.ToInt16(textQty.Text);
            }
            catch
            {
                iQty = 0;
            }
            gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["Qty"], iQty);
        }

        private void gridView1_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.FieldName == "")
            {
                e.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void cboUnitMeasure_SelectedIndexChanged(object sender, EventArgs e)
        {
            string sItemCode = "";
            string sUoM = "";

            int iFocusRowHandle = gridView1.FocusedRowHandle;

            try
            {
                sItemCode = gridView1.GetRowCellValue(iFocusRowHandle, gridView1.Columns["ItemCode"]).ToString();

                DevExpress.XtraEditors.ComboBoxEdit oCombo = (DevExpress.XtraEditors.ComboBoxEdit)sender;

                sUoM = oCombo.Text;

                UoMManager oManager = new UoMManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                double _PackSize = oManager.GetPackSize(sItemCode, sUoM);
                oManager.Close();

                gridView1.SetRowCellValue(iFocusRowHandle, gridView1.Columns["CQty"], _PackSize);



                int iCount = -1;
                int[] oRow = gridView1.GetSelectedRows();
                iCount = oRow[0];

                DevExpress.XtraEditors.TextEdit oTextQty = (DevExpress.XtraEditors.TextEdit)sender;

                double _QUANTITY = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["Qty"]).ToString());
                double _CQUANTITY = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["CQty"]).ToString());
                string _ITEMCODE = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemCode"]).ToString();
                double _UNITPRICE = Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["UnitPrice"]).ToString());
                double _TOTAL_DISCOUNT = (_QUANTITY * _CQUANTITY) * Convert.ToDouble(gridView1.GetRowCellValue(iCount, gridView1.Columns["Discount"]).ToString());

                double _AMOUNT = ((_QUANTITY * _CQUANTITY) * _UNITPRICE) - _TOTAL_DISCOUNT;
                gridView1.SetRowCellValue(iCount, gridView1.Columns["TotalLineDisc"], _TOTAL_DISCOUNT);
                gridView1.SetRowCellValue(iCount, gridView1.Columns["Amount"], _AMOUNT);
                bool IsChecked = false;
                gridView1.SetRowCellValue(iCount, gridView1.Columns["IsFree"], IsChecked);
                ComputeTotal();
                ApplyVolumeDiscount();
            }
            catch
            {
            }


        }

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            //int iFocusedRowHandle = e.RowHandle;

            //BindUoM(gridView1.GetRowCellValue(iFocusedRowHandle, gridView1.Columns["ItemCode"]).ToString(), cboUnitMeasure);
        }

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            try
            {
                int iFocusedRowHandle = e.FocusedRowHandle;

                BindUoM(gridView1.GetRowCellValue(iFocusedRowHandle, gridView1.Columns["ItemCode"]).ToString(), cboUnitMeasure);
            }
            catch
            {
            }
        }

        private void cboUnitMeasure_EditValueChanged(object sender, EventArgs e)
        {
            DevExpress.XtraEditors.ComboBoxEdit oCboUoM = (DevExpress.XtraEditors.ComboBoxEdit)sender;
            string sUoM = "";
            try
            {
                sUoM = Convert.ToString(oCboUoM.Text);
            }
            catch
            {
                sUoM = "";
            }
            if (sUoM != "")
            {
                gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["UoM"], sUoM);
            }
        }

        private void ribbonControl1_Click(object sender, EventArgs e)
        {

        }

        private void SalesOrder_Resize(object sender, EventArgs e)
        {

            if (this.Height >= 554)
            {
                gridControl1.Height = this.Height - 369;
                lblSalesMan.Top = this.Height - 176;
                cboSalesman.Top = this.Height - 176;

                lblGrossAmount.Top = this.Height - 176;
                txtGrossAmount.Top = this.Height - 176;

                lblRemarks.Top = this.Height - 150;
                txtRemarks.Top = this.Height - 150;

                lblTotalLineDiscount.Top = this.Height - 150;
                txtTotalLineDiscount.Top = this.Height - 150;

                lblDiscount.Top = this.Height - 123;
                txtDisc1.Top = this.Height - 123;
                txtDisc2.Top = this.Height - 123;
                txtDisc3.Top = this.Height - 123;
                txtDisc4.Top = this.Height - 123;
                txtTotalDiscount.Top = this.Height - 123;

                lblVAT.Top = this.Height - 98;
                txtVAT.Top = this.Height - 98;

                lblNetAmt.Top = this.Height - 71;
                txtNetAmt.Top = this.Height - 71;

                btnAdd.Top = this.Height - 77;
                btnCancel.Top = this.Height - 77;
                btnCopyToDelivery.Top = this.Height - 77;
                btnCreateTransfer.Top = this.Height - 77;
            }
            else
            {
                gridControl1.Height = 184;

                lblSalesMan.Top = 377;
                cboSalesman.Top = 377;

                lblGrossAmount.Top = 377;
                txtGrossAmount.Top = 377;

                lblRemarks.Top = 403;
                txtRemarks.Top = 403;

                lblTotalLineDiscount.Top = 403;
                txtTotalLineDiscount.Top = 403;

                lblDiscount.Top = 430;
                txtDisc1.Top = 430;
                txtDisc2.Top = 430;
                txtDisc3.Top = 430;
                txtDisc4.Top = 430;
                txtTotalDiscount.Top = 430;

                lblVAT.Top = 455;
                txtVAT.Top = 455;

                lblNetAmt.Top = 482;
                txtNetAmt.Top = 482;

                btnAdd.Top = 476;
                btnCancel.Top = 476;
                btnCopyToDelivery.Top = 476;
                btnCreateTransfer.Top = 476;
            }

            if (this.Width >= 856)
            {
                gridControl1.Width = this.Width - 39;

                lblDocNo.Left = this.Width - 269;
                lblDocStatus.Left = this.Width - 269;
                lblPostDate.Left = this.Width - 269;
                lblValidUntilDeliveryDate.Left = this.Width - 269;
                lblDocumentDate.Left = this.Width - 269;

                txtDocumentNumber.Left = this.Width - 152;
                txtStatus.Left = this.Width - 152;
                dtPostDate.Left = this.Width - 152;
                dtDeliveryDate.Left = this.Width - 152;
                dtDocDate.Left = this.Width - 152;

                lblGrossAmount.Left = this.Width - 422;
                lblTotalLineDiscount.Left = this.Width - 422;
                lblDiscount.Left = this.Width - 422;
                lblVAT.Left = this.Width - 422;
                lblNetAmt.Left = this.Width - 422;


                txtGrossAmount.Left = this.Width - 315;
                txtDisc1.Left = this.Width - 315;
                txtDisc2.Left = this.Width - 262;
                txtDisc3.Left = this.Width - 207;
                txtDisc4.Left = this.Width - 152;
                txtTotalLineDiscount.Left = this.Width - 315;
                txtTotalDiscount.Left = this.Width - 97;
                txtVAT.Left = this.Width - 315;
                txtNetAmt.Left = this.Width - 315;



            }
            else
            {
                gridControl1.Width = 856;

                lblDocNo.Left = 587;
                lblDocStatus.Left = 587;
                lblPostDate.Left = 587;
                lblValidUntilDeliveryDate.Left = 587;
                lblDocumentDate.Left = 587;



                txtDocumentNumber.Left = 704;
                txtStatus.Left = 704;
                dtPostDate.Left = 704;
                dtDeliveryDate.Left = 704;
                dtDocDate.Left = 704;

                lblGrossAmount.Left = 434;
                lblTotalLineDiscount.Left = 434;
                lblDiscount.Left = 434;
                lblVAT.Left = 434;
                lblNetAmt.Left = 434;

                txtGrossAmount.Left = 542;
                txtDisc1.Left = 542;
                txtDisc2.Left = 594;
                txtDisc3.Left = 649;
                txtDisc4.Left = 704;
                txtTotalDiscount.Left = 759;
                txtTotalLineDiscount.Left = 542;
                txtVAT.Left = 542;
                txtNetAmt.Left = 542;
            }
        }

        private void gridControl1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {

                cntxtRightClickMenu.Show(Cursor.Position);
            }
        }

        private void insertNewRowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int iRowHandle = gridView1.FocusedRowHandle;

            DataTable dt = this.OrderLineItems;
            DataRow _BlankRow = dt.NewRow();

            dt.Rows.InsertAt(_BlankRow, iRowHandle);

            gridControl1.DataSource = dt;
            gridControl1.Refresh();

            gridView1.FocusedRowHandle = iRowHandle;

        }

        private void addRowToolStripMenuItem_Click(object sender, EventArgs e)
        {


            if (gridView1.IsLastRow == false)
            {
                gridView1.MoveLast();
            }

            string _ItemCode = "";

            _ItemCode = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["ItemCode"]).ToString();

            if (_ItemCode.Trim() == "")
            {
                MessageBox.Show("New row is already exists!!!", "Add Row", MessageBoxButtons.OK, MessageBoxIcon.Information);

                gridView1.MoveLast();
                gridView1.FocusedColumn = gridView1.Columns["ItemCode"];
                gridView1.ShowEditor();
            }
            else
            {
                gridView1.AddNewRow();
                
                txtCardCode.Focus();
                
                gridControl1.Select();
                gridView1.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
                gridView1.FocusedColumn = gridView1.VisibleColumns[1];
                gridView1.ShowEditor();
            }

        }

        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnCopyToDelivery_Click(sender, e);
        }

        private void duplicateToolMenu_Click(object sender, EventArgs e)
        {

        }

        private void deleteRowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int iCount = gridView1.FocusedRowHandle;


            if (txtStatus.Text == "Draft")
            {
                if (MessageBox.Show("Are you sure you want to delete this Row?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {

                    if (gridView1.IsLastRow)
                    {
                        string sItemCode = "";

                        iCount = gridView1.FocusedRowHandle;
                        sItemCode = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemCode"]).ToString();


                        if (sItemCode != "")
                        {
                            gridView1.DeleteRow(iCount);
                            gridView1.AddNewRow();
                        }


                        gridView1.RefreshData();

                    }
                    else
                    {
                        iCount = gridView1.FocusedRowHandle;

                        gridView1.DeleteRow(iCount);
                        gridView1.RefreshData();
                    }
                    
                    ComputeTotal();
                }
            }
                    
        }

        private void txtStoreCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AddressBookManager oManager = new AddressBookManager();
                TaxManager oTxManager = new TaxManager();
                DataTable _TABLE = new DataTable();

                try
                {

                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();

                    _TABLE = oManager.GetByStoreCode(txtStoreCode.Text, "Customer");

                    oManager.Close();

                    int iCount = _TABLE.Rows.Count;

                    if (iCount == 0)
                    {
                        #region if no data return during enter
                        FND_BP _SearchBP = new FND_BP();

                        AddressBookManager oBPManager = new AddressBookManager();

                        try
                        {
                            _SearchBP.ConnectionString = this.ConnectionString;
                            _SearchBP.SearchIndex = 2;
                            _SearchBP.BusinessPartnerType = "Customer";
                            _SearchBP.SetSearchByStoreCode(txtStoreCode.Text);

                            _SearchBP.ShowDialog();

                            txtStoreCode.Text = _SearchBP.StoreCode;
                            txtCardCode.Text = _SearchBP.CardCode;
                            txtCardName.Text = _SearchBP.CardName;
                            txtBillTo.Text = _SearchBP.Address;
                            txtPaymentTerms.Text = _SearchBP.PaymentTerm.ToString();
                            txtContactPerson.Text = _SearchBP.ContactPerson;
                            this.DefaultPriceList = _SearchBP.PriceList;
                            this.VATCode = _SearchBP.VATCode;
                            try
                            {
                                txtDisc1.Text = _SearchBP.Discount1.ToString() + "%";
                                txtDisc2.Text = _SearchBP.Discount2.ToString() + "%";
                                txtDisc3.Text = _SearchBP.Discount3.ToString() + "%";
                                txtDisc4.Text = _SearchBP.Discount4.ToString() + "%";
                            }
                            catch
                            {
                            }


                            oTxManager.ConnectionString = this.ConnectionString;
                            oTxManager.Open();


                            this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();

                            this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;



                            oTxManager.Close();

                            if (_SearchBP.BuyerSalesMan != "")
                            {
                                cboSalesman.EditValue = _SearchBP.BuyerSalesMan;
                            }

                            _SearchBP.Dispose();
                        }
                        catch
                        {
                        }
                        #endregion
                        return;
                    }

                    DataRow oRow = _TABLE.Rows[0];

                    txtStoreCode.Text = oRow["StoreCode"].ToString();
                    txtCardCode.Text = oRow["BPCode"].ToString();
                    txtCardName.Text = oRow["BPName"].ToString();
                    txtBillTo.Text = oRow["Address"].ToString();
                    txtPaymentTerms.Text = oRow["PaymentTerm"].ToString();
                    txtContactPerson.Text = oRow["ContactPerson"].ToString(); ;
                    this.DefaultPriceList = oRow["PriceList"].ToString(); ;
                    this.VATCode = oRow["VATCode"].ToString();

                    try
                    {
                        txtDisc1.Text = oRow["Disc1"].ToString() + "%";
                        txtDisc2.Text = oRow["Disc2"].ToString() + "%";
                        txtDisc3.Text = oRow["Disc3"].ToString() + "%";
                        txtDisc4.Text = oRow["Disc4"].ToString() + "%";
                    }
                    catch
                    {
                    }

                    //cboCurrency.Text 
                    oTxManager.ConnectionString = this.ConnectionString;
                    oTxManager.Open();


                    this.VATRate = oTxManager.GetVATRate(this.VATCode).ToString();

                    this.IsInclusive = oTxManager.IsInclusive(this.VATCode) == "Y" ? true : false;


                    oTxManager.Close();

                    if (oRow["SMCODE"].ToString() != "")
                    {
                        cboSalesman.EditValue = oRow["SMCODE"].ToString();
                    }
                }
                catch
                {
                }
            }
        }

        private void cboLocation_EditValueChanged(object sender, EventArgs e)
        {
            BindWarehouseAndExclude(cboLocation.Text);
        }

        private void btnCreateTransfer_Click(object sender, EventArgs e)
        {
            ConsignmentTransfer oForm = new ConsignmentTransfer();

            oForm.ConnectionString = this.ConnectionString;
            oForm.ActiveUserID = this.ActiveUserID;
            oForm.DefaultWarehouse = this.DefaultWarehouse;
            oForm.IsMultipleWarehouse = this.IsMultipleWarehouse;

            oForm.MdiParent = this.MdiParent;
            oForm.CopyConsignmentOrderToConsignmentTransfer(txtDocumentNumber.Text);
            oForm.Show();
        }
    }
}